﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;


namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class ServiceCheckMaxMemorySetting : IssueTypeCheckBase
    {

        public ServiceCheckMaxMemorySetting()
        {
            IssueTypeId = 2019;
        }

        public override void Check()
        {
            try
            {
                // Database check AutoShrink is enabled 
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);


                // Query for Databases with auto shrink enabled
                ThresholdValue thresholdValue = dc.ThresholdValues.FirstOrDefault(t => t.IssueTypeID == IssueTypeId && t.ThresholdValueID == 1);
                var Qry = from s in dc.Servers
                          from sv in s.Services
                          from ss in sv.ServiceSettings
                          where ss.Name == "max server memory (MB)"
                          where (int)ss.Value < (thresholdValue.Value * s.MemoryInGB*1024) / 100
                          select sv;


                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);
     
                foreach (var service in Qry)
                {

                    //Create new Issue

                    Issue issue = new Issue();
                    issue.IssueType = issueType;
                    issue.TargetId = service.ServiceID;
                    issue.Description = issueType.Description.Replace("{ServiceName}", service.Name);

                    dc.Issues.InsertOnSubmit(issue);
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

    }
}
